package zkdemo;

import org.apache.curator.framework.CuratorFramework;
import org.apache.curator.framework.CuratorFrameworkFactory;
import org.apache.curator.framework.recipes.leader.LeaderSelector;
import org.apache.curator.framework.recipes.leader.LeaderSelectorListenerAdapter;
import org.apache.curator.retry.ExponentialBackoffRetry;
import org.junit.Before;
import org.junit.Test;

public class Curator_MasterSelect {
	CuratorFramework client;
	
	@Before
	public void init() {
		client = CuratorFrameworkFactory.builder()
				.connectString("192.168.10.188:2181")
				.sessionTimeoutMs(5000)
				.connectionTimeoutMs(3000)
				.retryPolicy(new ExponentialBackoffRetry(1000, 3))
				.namespace("zk-book")
				.build();
		client.start();
	}
	
	//master选举
	@Test
	public void test() throws InterruptedException {
		LeaderSelector selector = new LeaderSelector(client, "/leaderpath", new LeaderSelectorListenerAdapter() {
			@Override
			public void takeLeadership(CuratorFramework client) throws Exception {
				System.out.println("----成为Master----");
				Thread.sleep(3000);
				System.out.println("----完成Master操作，释放Master权利----");
			}
		});
		
		selector.autoRequeue();
		selector.start();
		Thread.sleep(Long.MAX_VALUE);
		selector.close();
	}
}
